package com.cnunicom.modules.tra.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.event.AnalysisEventListener;
import com.cnunicom.common.exception.RRException;
import com.cnunicom.common.utils.*;
import com.google.zxing.WriterException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.cnunicom.modules.tra.entity.UnitEntity;
import com.cnunicom.modules.tra.service.UnitService;
import org.springframework.web.multipart.MultipartFile;

import javax.print.DocFlavor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;


/**
 * 单位表，与单位会员表关联
 *
 * @author dzygod
 * @email dingziyuan0@gmail.com
 * @date 2019-11-27 16:44:19
 */
@RestController
@RequestMapping("tra/unit")
public class UnitController {
    @Autowired
    private UnitService unitService;
    @Autowired
    private QRCodeUtils qrCodeUtils;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("tra:unit:list")
    public R list(@RequestParam Map<String, Object> params) {
//        PageUtils page = unitService.queryPage(params);
        List<Object> objects = unitService.queryUnitMebHisPage(params);
        PageUtils page = (PageUtils)objects.get(0);
        HashMap<String, String> map = (HashMap<String, String>) objects.get(1);
        return R.ok().put("page", page).put("list",map);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("tra:unit:info")
    public R info(@PathVariable("id") Long id) {
        UnitEntity unit = unitService.getById(id);

        return R.ok().put("unit", unit);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("tra:unit:save")
    public R save(@RequestBody @Valid UnitEntity unit) {
        long unitId = new SnowflakeDistributeId(0, 0).nextId();
        unit.setId(unitId);
        unit.setQrCodeUrl(qrCodeUtils.packageUrlForLink(Constant.QRcodeAddress.UNIT_PROD.getValue() + unitId
                ,"https://www.ycbg.vip/group1/M00/00/09/rBD0tF7g80CACrPqAA182YJn5zo816.png"
                ,new String((unit.getName() + "会员注册码").getBytes(StandardCharsets.UTF_8))));
        unit.setCreateTime(DateUtils.getDateTime());
        unitService.save(unit);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("tra:unit:update")
    public R update(@RequestBody UnitEntity unit) {
        unitService.updateById(unit);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("tra:unit:delete")
    public R delete(@RequestBody Long[] ids) {
        unitService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 导入
     */
    @RequestMapping("/importExcel")
    public R importExcel(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            throw new RRException("导入文件不能为空");
        }
        AnalysisEventListener<UnitEntity> listener = ExcelUtils.getListener(this.batchInsert());
        try {
            EasyExcel.read(file.getInputStream(),UnitEntity.class,listener).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ok();
    }

    /**
     * 导出
     */
    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletResponse httpServletResponse) throws IOException {
        httpServletResponse.setCharacterEncoding("UTF-8");
        String fileName = URLEncoder.encode("单位表", "UTF-8");
        httpServletResponse.setContentType("application/vnd.ms-excel");
        httpServletResponse.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        httpServletResponse.setHeader("content-disposition", "attachment;filename=" + fileName +".xlsx");

        EasyExcel.write(httpServletResponse.getOutputStream(), UnitEntity.class).sheet("单位表sheet").doWrite(unitService.list());
    }

    /**
     * 导入业务逻辑处理
     * @return
     */
    private Consumer<List<UnitEntity>> batchInsert() {
        return units -> unitService.saveBatch(units);
    }


}
